//
//  WBOAuthController.swift
//  微博
//
//  Created by Mstarc on 2016/12/3.
//  Copyright © 2016年 Mstarc. All rights reserved.
//

import UIKit
import SVProgressHUD
//通过web加载新浪微博授权页面控制器
class WBOAuthController: UIViewController {
    private lazy var webView = UIWebView()
    

    override func loadView() {
        view = webView
        webView.delegate = self
        view.backgroundColor = UIColor.white
        //取消webView滚动
        webView.scrollView.isScrollEnabled = false
        title = "登录新浪微博"
        //导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBackBtn: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFile))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURI)"
        //1>.确定要访问的资源
        guard  let url = URL(string: urlString) else {
            return
        }
       
        //2>.建立请求
        let request = URLRequest(url: url)
        
        //3>.加载请求
        webView.loadRequest(request)
        
        // Do any additional setup after loading the view.
    }

    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //MARK - 监听方法
    
   @objc fileprivate func close(){
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    //自动填充  - webView的注入 直接通过js修改 本地浏览器中 缓存的页面内容
    //点击自动填充按钮 , 执行submit 将本地数据提交给服务器
    @objc private func autoFile(){
    //准备js 
    let js = "document.getElementById('userId').value = 'xie1990jian@sina.cn';" + "document.getElementById('passwd').value = '';"
    //让webView 执行 js  - webView的注入
    webView.stringByEvaluatingJavaScript(from: js)
    
    }
    

}


extension WBOAuthController:UIWebViewDelegate{
    
    
    /// webView 将要加载数据
    ///
    /// - parameter webView:        webView
    /// - parameter request:        要加载的请求
    /// - parameter navigationType: 导航类型
    ///
    /// - returns: 是否加载request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //确认思路:
        //1.如果请求地址包含 http://baidu.com 不加载页面 / 否则加载页面
        
        if request.url?.absoluteString.hasPrefix(WBRedirectURI) == false {
            return true
        }
        print("加载请求:----\(request.url?.absoluteString)")
        print("加载请求:----\(request.url?.query)")
        //2.从 http://baidu.com 回调地址中'查找字符串'   'code='
         //如果有 授权成功 没有则失败
        if request.url?.query?.hasPrefix("code=") == false {
            print("取消授权")
            close()
            return false
        }
       
        
        print("加载请求\(request.url?.relativeString)")
       
        //3.从query 字符串中取出授权码 
        //代码走到此处 url中一定有 查询字符串  并且包含code=
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        //获取授权码
        print("获取授权码:\(code)")
        //4.使用授权码 (换取)AccessToken
        WBNetworkManager.shared().loadAccessToken(code: code)
        
        return true
        
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}

